package com.camus.verify.biz.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import com.camus.utils.BigDecimalUtils;
import com.camus.verify.bo.MatchBO;
import com.camus.verify.bo.MatchParam;
import com.camus.verify.entity.VerifyTask;
import com.camus.verify.entity.VerifyTaskAp;
import com.camus.verify.entity.VerifyTaskInvoice;

import cn.hutool.json.JSONUtil;

/**
 * 发票与台账多对多匹配整体相等
 * 
 * @author jie.deng
 *
 */
@Service
@Order(value = 1)
public class OverallEqMatchHandler extends AbstractMatchHandler {

	@Override
	public List<MatchBO> match(final VerifyTask task, final List<VerifyTaskInvoice> invoiceCandidateList,
			final List<VerifyTaskAp> apCandidateList) {
		List<MatchBO> resultList = new ArrayList<>();

		List<VerifyTaskInvoice> leftCandidateList = invoiceCandidateList.stream().filter(t -> t.getMatched() == 0)
				.collect(Collectors.toList());
		List<VerifyTaskAp> rightCandidateList = apCandidateList.stream().filter(t -> t.getMatched() == 0)
				.collect(Collectors.toList());
		if (CollectionUtils.isEmpty(leftCandidateList) || CollectionUtils.isEmpty(rightCandidateList)) {
			return resultList;
		}

		if (log.isInfoEnabled()) {
			log.info("多对多整体匹配,param={}",
					JSONUtil.toJsonStr(MatchParam.of(task, leftCandidateList, rightCandidateList)));
		}
		BigDecimal left = leftCandidateList.stream().map(VerifyTaskInvoice::getPendingVerifyAmt).reduce(BigDecimal.ZERO,
				BigDecimal::add);
		BigDecimal right = rightCandidateList.stream().map(VerifyTaskAp::getPendingVerifyAmt).reduce(BigDecimal.ZERO,
				BigDecimal::add);
		if (BigDecimalUtils.isEqualWithinTolerance(left, right, tolerance)) {
			resultList.add(buildResultBO(task, leftCandidateList, rightCandidateList));
		}
		if (log.isInfoEnabled()) {
			log.info("多对多整体匹配,返回值={}", JSONUtil.toJsonStr(resultList));
		}
		return resultList;
	}

	@Override
	public String getMatchHandlerName() {
		return "多对多整体匹配";
	}

}
